package players;

import java.util.ArrayList;

import staticClasses.Global;

public class Ball extends Agent{
	
	public double velocity;
	public int[] targeted_case = new int [2];
	int traveledDist = 0;
	ArrayList<int[]> path = null;
	
	
	public Ball(){}
	
	/**
	 * 
	 */
	@Override
	public void run(){
		try{
			int i=0;
			while(Global.play){
				synchronized (this) {
					this.wait();
				}
				if(i==19){
					i=0;
				}
				i++;
				exec();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	private void reset(){
		velocity=0;
		targeted_case[0] = this.getPosition()[0];
		targeted_case[1] = this.getPosition()[1];
		this.traveledDist=0;
	}
	
	private void exec(){
		if(Global.getBallOwner()!=null){
			try{
				this.setPosition(Global.getBallOwner().getPosition()[0], Global.getBallOwner().getPosition()[1]);
				this.reset();
			}catch(Exception e){}
		}
		else{
			if(this.targeted_case[0]!=0 && this.targeted_case[0]!=(Global.MapSize[0]-1) &&
			   this.targeted_case[1]!=0 && this.targeted_case[1]!=(Global.MapSize[1]-1)){
				double coeff = ((double)this.targeted_case[0]-(double)this.getPosition()[0])/
							   ((double)this.targeted_case[1]-(double)this.getPosition()[1]);
				if(this.targeted_case[1] < this.getPosition()[1]){
					double x = coeff*(0.0-(double)this.targeted_case[1])+(double)this.targeted_case[0];
					if(Math.round(x)<Global.MapSize[0] && x>=0){
						targeted_case[0] = (int)Math.round(x);
						targeted_case[1] = 0;
					}
				}
				else if(this.targeted_case[1] > this.getPosition()[1]){
					double x = coeff*((double)Global.MapSize[1]-(double)this.targeted_case[1])+(double)this.targeted_case[0];
					if(Math.round(x)<Global.MapSize[0] && x>=0){
						targeted_case[0] = (int)Math.round(x);
						targeted_case[1] = Global.MapSize[1]-1;
					}
				}
				else{
					if(targeted_case[0]>this.getPosition()[0]){
						targeted_case[0]=Global.MapSize[0]-1;
					}
					else if(targeted_case[0]<this.getPosition()[0]){
						targeted_case[0]=0;
					}
					else{
						targeted_case[0]=Global.center.x;
						targeted_case[1]=Global.MapSize[1]-1;
					}
				}
			}
			//traveled distance in a tick of 50ms
			double mov = (double)this.velocity;//set speed in km/h
			mov /= 3.6;//set speed in m/s
			mov /= 20;//set speed in m/tick
			mov *=10;//there are 10 square per meter
			path = Global.bresenham(this.getPosition()[0], this.getPosition()[1], this.targeted_case[0], this.targeted_case[1]);
			int dist = (int)Math.round(mov);
			if(dist<path.size()){
				this.setPosition(path.get((int)Math.round(mov))[0], path.get((int)Math.round(mov))[1]);
			}
			else{
				this.setPosition(path.get(path.size()-1)[0], path.get(path.size()-1)[1]);
			}
			
			this.velocity -= mov/5;
		}
	}
}
